package com.ruoyi.system.service.impl;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.http.HttpHelper;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.domain.CsvData;
import com.ruoyi.system.domain.vo.GetKlineDataVo;
import com.ruoyi.system.domain.vo.KlineAddVo;
import com.ruoyi.system.mapper.CsvDataMapper;
import com.ruoyi.system.mapper.TechnicalIndexMapper;
import com.ruoyi.system.service.ICsvDataService;
import com.ruoyi.system.service.ITechnicalIndexService;
import com.ruoyi.system.utils.CsvUtils;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.KlineMapper;
import com.ruoyi.system.domain.Kline;
import com.ruoyi.system.service.IKlineService;
import org.springframework.transaction.annotation.Transactional;

/**
 * K线图Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-03-19
 */
@Service
public class KlineServiceImpl implements IKlineService 
{
    @Autowired
    private KlineMapper klineMapper;
    @Autowired
    private CsvDataMapper csvDataMapper;

    @Autowired
    private TechnicalIndexMapper technicalIndexMapper;

    @Autowired
    private ITechnicalIndexService iTechnicalIndexService;



    /**
     * 查询K线图
     * 
     * @param id K线图主键
     * @return K线图
     */
    @Override
    public Kline selectKlineById(Long id)
    {
        return klineMapper.selectKlineById(id);
    }

    /**
     * 查询K线图列表
     * 
     * @param kline K线图
     * @return K线图
     */
    @Override
    public List<Kline> selectKlineList(Kline kline)
    {
        return klineMapper.selectKlineList(kline);
    }

    /**
     * 新增K线图
     * 
     * @param kline K线图
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public int insertKline(KlineAddVo kline)
    {
        Long userId = SecurityUtils.getUserId();
        //保存K线图
        Kline data = new Kline();
        BeanUtils.copyProperties(kline, data);
        data.setCreateTime(DateUtils.getNowDate());
        data.setUpdateTime(DateUtils.getNowDate());
        data.setUserId(userId);
        int i = klineMapper.insertKline(data);
        //保存K线图数据
        List<CsvData> csvData = CsvUtils.parseCSVFile(kline.getUrl());
        for (CsvData csvDatum : csvData) {
            csvDatum.setKlineId(data.getId());
            csvDatum.setUserId(userId);
            csvDataMapper.insertCsvData(csvDatum);
        }
        iTechnicalIndexService.saveTechnicalIndex(data,csvData);
        return i;
    }

    /**
     * 修改K线图
     * 
     * @param kline K线图
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public int updateKline(Kline kline)
    {
        kline.setUpdateTime(DateUtils.getNowDate());
        csvDataMapper.deleteCsvDataByKlineId(kline.getId());
        return klineMapper.updateKline(kline);
    }

    /**
     * 批量删除K线图
     * 
     * @param ids 需要删除的K线图主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public int deleteKlineByIds(Long[] ids)
    {
        for (Long id : ids) {
            csvDataMapper.deleteCsvDataByKlineId(id);
            technicalIndexMapper.deleteTechnicalIndexByKlineId(id);
        }
        return klineMapper.deleteKlineByIds(ids);
    }

    /**
     * 删除K线图信息
     * 
     * @param id K线图主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public int deleteKlineById(Long id)
    {
        csvDataMapper.deleteCsvDataByKlineId(id);
        technicalIndexMapper.deleteTechnicalIndexByKlineId(id);
        return klineMapper.deleteKlineById(id);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void getKlineData(GetKlineDataVo getKlineDataVo) {
        String downLoadPath="E:/bs/uploadPath/csvData/"+SecurityUtils.getUserId()+"_"+System.currentTimeMillis()+".csv";
        try {
            //调用python获取数据
            String url="http://127.0.0.1:5000/api/getData";

            String param="symbol="+getKlineDataVo.getSymbol()
                    +"&start_time="+getKlineDataVo.getStartTime()
                    +"&end_time="+getKlineDataVo.getEndTime()
                    +"&downLoadPath="+downLoadPath;
            HttpUtils.sendGet(url, param);

        }catch (Exception e) {
            new RuntimeException("获取数据失败！！");
        }
        //修改一下csv文件头部格式
        CsvUtils.InsertValueToCSV(downLoadPath);

        //保存数据
        try (BufferedReader reader = new BufferedReader(new FileReader(downLoadPath));
             CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT.withFirstRecordAsHeader())) {
            Long userId = SecurityUtils.getUserId();
            Date date = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            //保存K线图
            Kline data = new Kline();
            data.setUserId(userId);
            data.setKlineName(getKlineDataVo.getName());
            data.setKlineCode(getKlineDataVo.getSymbol());
            data.setCreateTime(DateUtils.getNowDate());
            data.setUpdateTime(DateUtils.getNowDate());
            data.setRemark("股票代码："+getKlineDataVo.getSymbol()+"（"+getKlineDataVo.getStartTime()+"到"+getKlineDataVo.getEndTime()+")");
            klineMapper.insertKline(data);
            //保存数据
            List<CsvData> csvDataList=new LinkedList<>();
            for (CSVRecord csvRecord : csvParser) {
                CsvData csvData=new CsvData();
                //long转Date
                csvData.setTimeStamp(dateFormat.parse(csvRecord.get("bob")));
                csvData.setStartPrice(new BigDecimal(csvRecord.get("open")));
                csvData.setMaxPrice(new BigDecimal(csvRecord.get("high")));
                csvData.setMinPrice(new BigDecimal(csvRecord.get("low")));
                csvData.setEndPrice(new BigDecimal(csvRecord.get("close")));
                csvData.setTurnover(Long.valueOf(csvRecord.get("volume")));
                csvData.setUserId(userId);
                csvData.setCreateTime(date);
                csvData.setUpdateTime(date);
                csvData.setKlineId(data.getId());
                csvDataList.add(csvData);
                csvDataMapper.insertCsvData(csvData);
            }
            iTechnicalIndexService.saveTechnicalIndex(data,csvDataList);


        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }catch (Exception e) {
            throw new RuntimeException("无数据！！");
        }


    }
}
